//
//  XPShareView.swift
//  PPKit
//
//  Created by xiaopin on 2019/8/21.
//  Copyright © 2019 PPKit. All rights reserved.
//  https://gitee.com/xiaopindev/PPKit
//  https://github.com/xiaopindev
//  https://xiaopin.cnblogs.com

import UIKit

enum ShareEventType:Int {
    /// 分享成功
    case success = 1
    /// 分享失败
    case failed = 2
    /// 分享取消
    case cancel = 3
    /// 查看原文
    case seeArticle = 4
    /// 提醒设置
    case tipSettings = 5
    /// 举报
    case jubao = 6
    /// 生成长图
    case generateLongImage = 7
}

/// 分享样式
///
/// statdard : 标准分享
/// user:用户分享
/// groupChat: 群聊分享
enum ShareStyle {
    /// 标准分享
    case standard
    /// 分享用户
    case user
    /// 群聊分享
    case groupChat
    /// 帖子分享
    case postShare
    /// 自定义：[SharePlatform]
    case custom
}

/// 分享平台
enum SharePlatform: String{
    case weibo = "wb"
    case weixin = "wx"
    case qq = "qq"
    case qqzone = "qqkj"
    case pyq = "pyq"
    case longImage = "longImage"
    case saveImage = "saveImage"
}

/// 通用分享弹出框
@objcMembers
class XPShareView: XPBaseView {

    /// 事件回调
    var eventClosure:((ShareEventType)->())?
    
    //MARK: 属性
    /// 分享的平台：
    private var sharePlatform = [SharePlatform]()
    /// 分享标题
    private var shareTitle:String = "无标题"
    /// 分享的摘要描述
    private var shareText:String = "无摘要"
    /// 分享的缩略图
    private var shareImageUrls = [kShareDefaultPic]
    /// 分享的连接地址
    private var shareLinkUrl:String = ""
    
    //数据源
    private var style:ShareStyle = .standard
    private var items = [String]()
    private var items2 = [String]()
    
    /// 背景透明滤镜
    private lazy var alphaView:UIView = {
        let view = UIView(frame: pp_frame(0, 0, self.width, self.height))
        view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        view.alpha = 0
        let alphaTap = UITapGestureRecognizer(target: self, action: #selector(alphaTapAction(_:)))
        view.addGestureRecognizer(alphaTap)
        return view
    }()

    /// 内容容器
    private lazy var contentView:UIView = {
        return UIView(frame: pp_frame(0, self.height, self.width, contentHeight))
    }()
    private lazy var titleView:UILabel = {
        //标题
        let label = UILabel(frame: pp_frame(0, 20, self.contentView.width, titleHeight))
        label.textAlignment = .center
        label.textColor = pp_color(.C222222)
        label.text = isSH() ? "分享" : "分享到"
        label.font = .boldSystemFont(ofSize: 15)
        return label
    }()
    private lazy var itemsView:UIScrollView = {
        let view = UIScrollView(frame: pp_frame(15, self.titleView.top + titleHeight, self.contentView.width-15, itemsHeight))
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.contentSize = CGSize(width: itemsWidth, height: itemsHeight)
        return view
    }()
    private lazy var lineView:UIView = {
        let view = UIView(frame: pp_frame(15, self.itemsView.top + itemsHeight, self.contentView.width - 30, lineHeight))
        view.backgroundColor = pp_color(.Seperator)
        return view
    }()
    private lazy var items2View:UIScrollView = {
        let view = UIScrollView(frame: pp_frame(15, self.lineView.top + lineHeight, self.contentView.width-15, items2Height))
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.contentSize = CGSize(width: items2Width, height: items2Height)
        return view
    }()
    
    private lazy var bottomView:UIView = {
        let view = UIView(frame: pp_frame(0, items2View.top + items2Height, self.width, pp_screen_tabbar_height))
        view.backgroundColor = pp_color(.CFFFFFF)
        return view
    }()
    /// 取消
    private lazy var btnCancel:UIButton = {
       let button = UIButton(type: .custom)
        button.frame = pp_frame(15, 0, bottomView.width-30, closeHeight)
        button.backgroundColor = pp_color(.CFFFFFF)
        button.cornerRadius = 8
        button.titleLabel?.font = .systemFont(ofSize: 13)
        button.setTitle("取消", for: .normal)
        button.setTitleColor(pp_color(.C222222), for: .normal)
        button.addTarget(self, action: #selector(cancelAction(_:)), for: .touchUpInside)
        return button
    }()
    
    private var labelWidth:CGFloat = 0.0,imageSize:CGFloat = 0.0,imageSpace:CGFloat = 0.0
    private var contentHeight:CGFloat = 0.0,titleHeight:CGFloat = 0.0,itemsHeight:CGFloat = 0.0,itemsWidth:CGFloat = 0.0,labelHeight:CGFloat = 0.0,lineHeight:CGFloat = 0.0,items2Width:CGFloat = 0.0,items2Height:CGFloat = 0.0,closeHeight:CGFloat = 0.0
        
    //MARK: 重载父类方法
    
    init(frame: CGRect, style:ShareStyle) {
        super.init(frame: frame)

        self.style = style
        initData()
        initSubViews()
    }
    
    init(frame: CGRect, platforms:[SharePlatform]) {
        super.init(frame: frame)

        self.style = .custom
        self.sharePlatform = platforms
        initData()
        initSubViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 初始化数据
    override func initData() {
        items.removeAll()
        items2.removeAll()
        
        //MARK: 数据源配置
        /* 数据源配置 Begin */
        //id,名称,正常图片，高亮图片
        if ShareSDK.isClientInstalled(.typeSinaWeibo) && sharePlatform.contains(.weibo) {
            items.append("20001,微博,share_weibo,share_weibo")
        }
        if ShareSDK.isClientInstalled(.subTypeWechatSession) && sharePlatform.contains(.weixin) {
            items.append("20002,微信,share_wechat,share_wechat")
        }
        if ShareSDK.isClientInstalled(.subTypeWechatTimeline) && sharePlatform.contains(.pyq) {
            items.append("20003,朋友圈,share_moment,share_moment")
        }
        if ShareSDK.isClientInstalled(.typeQQ) && sharePlatform.contains(.qq)  {
            items.append("20004,QQ,share_qq,share_qq")
        }
        if ShareSDK.isClientInstalled(.subTypeQZone) && sharePlatform.contains(.qqzone) {
            items.append("20005,QQ空间,share_zone,share_zone")
        }
        if sharePlatform.contains(.longImage){
            items.append("20006,生成长图,share_scct,share_scct")
        }
        if sharePlatform.contains(.saveImage){
            items.append("20009,保存图片,share_save,share_save")
        }
        
        items.append("20007,复制内容,share_copy,share_copy")
        items.append("20008,复制链接,share_copylink,share_copylink")
        
        items2.append("30001,查看全文,share_see,share_see")
        items2.append("30002,提醒设置,share_bell,share_bell")
        items2.append("30003,举报,share_jubao,share_jubao")
        /* 数据源配置 End */
        
        titleHeight = 30.0
        imageSize = 50.0
        labelWidth = imageSize
        labelHeight = 30.0
        itemsWidth = imageSize * items.count.f + 20.0 * items.count.f
        itemsHeight = 17.0 + imageSize + labelHeight + 17.0
        imageSpace = 20
        
        if items2.count > 0 {
            lineHeight = 0.5
            items2Width = imageSize * items2.count.f + 20.0 * items2.count.f
            items2Height = itemsHeight
        }
    
        closeHeight = 40.0
        contentHeight = 20 + titleHeight + itemsHeight + lineHeight + items2Height + pp_screen_tabbar_height
    }
    
    /// 初始化当前视图的子控件
    override func initSubViews() {
        addSubview(alphaView)
        addSubview(contentView)
        contentView.backgroundColor = pp_color(.CEEEEEE_272730)
        contentView.addSubview(titleView)
        contentView.addSubview(itemsView)
        contentView.addSubview(lineView)
        contentView.addSubview(items2View)
        bottomView.addSubview(btnCancel)
        contentView.addSubview(bottomView)
        
        for (i,item) in items.enumerated() {
            let array = item.components(separatedBy: ",")
            let tag = Int(array[0])
            let text = array[1]
            let normalImage = UIImage(named: array[2])
            
            tempX = i.f * imageSpace + i.f * imageSize
            tempY = 17
            
            let button = UIButton(type: .custom)
            button.tag = tag!
            button.frame = pp_frame(tempX, tempY, imageSize, imageSize)
            button.setImage(normalImage, for: .normal)
            button.addTarget(self, action: #selector(shareAction(_:)), for: .touchUpInside)
            
            tempY = button.origin.y + button.height
            let label = UILabel(frame: pp_frame(tempX, tempY, labelWidth, labelHeight))
            label.text = text
            label.textAlignment = .center
            label.textColor = pp_color(.C555555)
            label.font = .boldSystemFont(ofSize: 12)
            
            itemsView.addSubview(button)
            itemsView.addSubview(label)
        }
        
        for (i,item) in items2.enumerated() {
            let array = item.components(separatedBy: ",")
            let tag = Int(array[0])
            let text = array[1]
            let normalImage = UIImage(named: array[2])
            
            tempX = i.f * imageSpace + i.f * imageSize
            tempY = 17
            
            let button = UIButton(type: .custom)
            button.tag = tag!
            button.frame = pp_frame(tempX, tempY, imageSize, imageSize)
            button.setImage(normalImage, for: .normal)
            button.addTarget(self, action: #selector(moreAction(_:)), for: .touchUpInside)
            
            tempY = button.origin.y + button.height
            let label = UILabel(frame: pp_frame(tempX, tempY, labelWidth, labelHeight))
            label.text = text
            label.textAlignment = .center
            label.textColor = pp_color(.C555555)
            label.font = .boldSystemFont(ofSize: 12)
            
            items2View.addSubview(button)
            items2View.addSubview(label)
        }
    }
    
    //MARK: 自定义方法
    /// 分享框
    /// - Parameters:
    ///   - title: 标题
    ///   - summary: 摘要
    ///   - imageUrl: 图片链接
    ///   - linkUrl: 跳转链接
    func share(_ title:String, _ summary:String, _ imageUrl:[String], _ linkUrl:String){
        shareTitle = title
        shareText = summary
        shareImageUrls = imageUrl.count > 0 ? imageUrl : [kShareDefaultPic]
        shareLinkUrl = linkUrl
        pp_keyWindow()?.addSubview(self)
        show()
    }
    
    /// 弹出分享框
    func show(){
        UIView.animate(withDuration: 0.1, animations: {
            self.alphaView.alpha = 1
        }, completion: { (finished) in
            UIView.animate(withDuration: 0.2, animations: {
                self.contentView.top = self.height - self.contentView.height
            })
        })
    }
    
    /// 隐藏
    func hide(){
        UIView.animate(withDuration: 0.2, animations: {
            self.contentView.top = self.height
        }, completion: { (finished) in
            UIView.animate(withDuration: 0.2, animations: {
                self.alphaView.alpha = 0
            }, completion: { (finished) in
                self.removeFromSuperview()
            })
        })
    }
    
    //MARK: 事件通知
    /// 半透明背景点击事件
    func alphaTapAction(_ sender:Any){
        hide()
    }
    
    /// 分享事件
    func shareAction(_ button:UIButton){
        var platformType:SSDKPlatformType = .typeUnknown
        switch button.tag {
        case 20001:
            platformType = .typeSinaWeibo
        case 20002:
            platformType = .subTypeWechatSession
        case 20003:
            platformType = .subTypeWechatTimeline
        case 20004:
            platformType = .typeQQ
        case 20005:
            platformType = .subTypeQZone
        case 20006:
            //生成长图没有类型，用打印类型代替
            platformType = .typePrint
        case 20007:
            platformType = .typeCopy
        case 20008:
            //复制链接没有类型，暂用email代替
            platformType = .typeMail
        case 20009:
            //保存图片没有类型，暂用有道代替
            platformType = .typeYouDaoNote
        default:
            break
        }
        
        if platformType == .typeCopy {
            let copyStr = "【\(shareTitle)】\(shareText) 点击链接查看详情>>\(shareLinkUrl)(分享来自 @NNScore)"
            UIPasteboard.general.string = copyStr
            //复制分享内容成功，赶紧扩散造起来吧！
            showAlert("Alert_CopyShareContent")
            return
        }
        
        //复制链接用email代替
        if platformType == .typeMail {
            let copyStr = shareLinkUrl
            UIPasteboard.general.string = copyStr
            //复制链接成功
            showAlert("Alert_CopyShareLink")
            return
        }
        
        //生成长图用打印类型代替
        if platformType == .typePrint {
            eventClosure?(.generateLongImage)
            hide()
            return
        }
        
        //保存图片用有道类型代替
        if platformType == .typeYouDaoNote {
            guard let imageUrl = shareImageUrls.first,let url = URL(string: imageUrl) else{return}
            guard let data = try? Data.init(contentsOf: url) else { return }
            guard let image = UIImage(data: data) else{return}
            UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveImage(image:didFinishSavingWithError:contextInfo:)), nil)
            //保存成功
            showAlert("Alert_SaveDone")
            eventClosure?(.success)
            removeFromSuperview()
            return
        }
        
        //创建分享消息对象
        let params = NSMutableDictionary()
    
        switch platformType {
        case .typeSinaWeibo:
            let appendedText = "【\(shareTitle)】\(shareText) (分享来自 @NNScore)"
            params.ssdkSetupSinaWeiboShareParams(byText: appendedText, title: shareTitle, images: shareImageUrls, video: "", url: URL(string: shareLinkUrl), latitude: 0, longitude: 0, objectID: "", isShareToStory: false, type: .webPage)
        default:
            //默认模式
            params.ssdkSetupShareParams(byText: shareText, images: shareImageUrls, url: URL(string: shareLinkUrl), title: shareTitle, type: .auto)
        }
        
        //调用分享接口
        ShareSDK.share(platformType, parameters: params) { [weak self](state, userData, contentEntity, error) in
            switch state {
            case .success:
                showAlert("MT_Share_Done")
                self?.eventClosure?(.success)
                self?.removeFromSuperview()
            case .fail:
                showAlert("MT_Share_Failed")
                self?.eventClosure?(.failed)
                PPLog("分享失败, 原因：\(String(describing: error?.localizedDescription))")
            case .cancel:
                //showAlert("MT_Share_Cancel")
                self?.eventClosure?(.cancel)
            default:break
            }
        }
    }
    
    /// 更多操作事件
    func moreAction(_ button:UIButton){
        var eventType:ShareEventType?
        switch button.tag {
        case 30001:
            eventType = .seeArticle
        case 30002:
            eventType = .tipSettings
        case 30003:
            eventType = .jubao
        default:
            break
        }
        guard let type = eventType else { return }
        eventClosure?(type)
    }

    func cancelAction(_ button:UIButton){
        hide()
    }
    
    //MARK: 委托代理
    func saveImage(image:UIImage, didFinishSavingWithError error:Error?, contextInfo:AnyObject){
        if error == nil {
            //保存成功
            showAlert("Alert_SaveDone")
        }else{
            showAlert("Alert_SaveFailed")
        }
    }
}
